import React, { createContext, useState, lazy, useEffect } from "react";
import lazyLoad from "../utils/LazyLoad";
import Icon, {
  UserOutlined,
  SnippetsOutlined,
  UserDeleteOutlined,
} from "@ant-design/icons";

import HomeSvgIcon from "./svgIcons/HomeSvgIcon";

export const context = createContext({});

const HeartIcon = (props) => <Icon component={SvgIcons} {...props} />;
// 本地menu菜单
let menus = [
  {
    key: "/layouts/home",
    active: "home",
    icon: <HomeSvgIcon />,
    element: lazyLoad(lazy(() => import("../view/home/Home.jsx"))),
    label: "首页",
  },
  {
    key: "/layouts/order",
    icon: <SnippetsOutlined />,
    label: "订单",
    roles: ["admin"],
    children: [
      {
        key: "/layouts/order/whole",
        active: "order",
        element: lazyLoad(lazy(() => import("../view/order/OrderWhole.jsx"))),
        roles: ["admin"],
        label: "全部列表",
      },
      {
        key: "/layouts/order/list",
        active: "order",
        element: lazyLoad(lazy(() => import("../view/order/OrderList.jsx"))),
        roles: ["admin"],
        label: "我的列表",
      },
    ],
  },
  {
    key: "/layouts/user",
    icon: <UserDeleteOutlined />,
    label: "个人中心",
    roles: ["admin", "editor"],
    children: [
      {
        key: "/layouts/user/info",
        active: "user",
        element: lazyLoad(lazy(() => import("../view/user/UserInfo.jsx"))),
        roles: ["admin", "editor"],
        label: "个人信息",
      },
      {
        key: "/layouts/user/list",
        active: "user",
        element: lazyLoad(lazy(() => import("../view/user/UserList.jsx"))),
        roles: ["admin"],
        label: "个人列表",
      },
    ],
  },
];

/**
 * 根据role角色生成侧边栏菜单
 * @param {*} role
 * @returns
 */
function findRoles(role) {
  const arr = [];

  function findInfo(data, parent) {
    data.forEach((item) => {
      const { children, ...info } = item;
      //   children存在查找子集
      if (children) {
        info.children = [];
        findInfo(children, info.children);
        // 没有子节点就删除子节点
        info.children.length == 0 ? delete info.children : null;
      }
      //children不存在就判断有没有权限
      if (info.roles) {
        // 有权限的情况下就判断有没有父节点，有父节点就是有二级路由，没有父节点就是一级路由，没有嵌套
        if (info.roles?.includes(role)) {
          parent ? parent.push(info) : arr.push(info);
        }
      } else {
        parent ? parent.push(info) : arr.push(info);
      }
    });
  }

  findInfo(menus);
  return arr;
}

/**
 * 根据侧边栏实现路由信息的扁平化处理
 * @param {*} menus
 * @returns
 */
function flatRoutes(menus) {
  const arr = [];
  function findInfo(data) {
    data.forEach((item) => {
      const { children, ...info } = item;
      arr.push(info);
      if (children) {
        findInfo(children);
      }
    });
  }
  findInfo(menus);
  return arr;
}

// 实现动态路由的hooks必须
export default function AppProvider({ children }) {
  // 初始化的时候从本地存储获取角色信息
  let defaultMenus = [];
  let defaultRoutes = [];
  const oldRole = sessionStorage.getItem("role");
  console.log(oldRole, "oldRole");
  if (oldRole) {
    defaultMenus = findRoles(oldRole);
    if (defaultMenus && defaultMenus.length > 0) {
      defaultRoutes = flatRoutes(defaultMenus);
    }
  }
  // 侧边栏
  const [menus, setMenus] = useState(defaultMenus);
  // 路由
  const [routes, setRoutes] = useState(defaultRoutes);
  //根据当前角色生成路由信息和侧边栏信息
  const resetMenus = (role) => {
    // 此处重置菜单数据和路由数据
    const temMenu = findRoles(role);
    setMenus(temMenu);
    setRoutes(flatRoutes(temMenu));
  };
  // menus，routes,resetMenus,在useContext中可以拿到
  return (
    <context.Provider value={{ menus, routes, resetMenus }}>
      {children}
    </context.Provider>
  );
}
